package com.itheima.health.service.impl;

import com.itheima.health.common.RedisConst;
import com.itheima.health.service.MobileValidateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class MobileValidateCodeServiceImpl implements MobileValidateCodeService {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public void sendValidateCode(String validateCodeType, String telephone) {
     //生成验证码
        int code=(int) (1000 + new SecureRandom().nextDouble() * 8999);
        code=1234;
        //保存到缓存redis
        String redisKey=RedisConst.VALIDATE_CODE_PREFIX + validateCodeType +":"+ telephone;
         redisTemplate.boundValueOps(redisKey).set(String.valueOf(code),5*60L, TimeUnit.SECONDS);
    }
    @Override
    public boolean checkValidateCode(String validateCodeType, String phone, String code) {
        log.info("[短信-校验验证码]type:{},phone:{},code:{}", validateCodeType, phone, code);
        String redisKey = RedisConst.VALIDATE_CODE_PREFIX + validateCodeType + ":" + phone;
        //查询redis里的值
        String expectVal = (String) redisTemplate.boundValueOps(redisKey).get();
        //对比是否匹配
        if (!StringUtils.isEmpty(expectVal) && expectVal.equals(code)) {
            //如果匹配则删除redis并返回true
            redisTemplate.delete(redisKey);
            return true;
        } else {
            //如果不匹配则返回false
            return false;
        }

    }


}
